<?php
namespace app\admin\controller;
use think\Session;
use think\Loader;
use app\model\Order;
use app\model\AdminUsers;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

class OrderController extends BackendController
{
    protected $order;
    protected $pageNum;

	protected function _initialize(){
        parent::_initialize();
		$this->order = new Order();
	}

	public function index(){

        $time['startTime'] = $this->request->has('starttime') ? $this->request->param('starttime') : null;
        $time['endTime'] = $this->request->has('endtime') ? $this->request->param('endtime') : null;
        $status = $this->request->param('status');

        $status = ($status != null)||($status=='0') ? $status : 'all'; //防止状态0被过滤

        $startTime = $time['startTime'] ? strtotime($time['startTime']) : 0;
        $endTime = $time['endTime'] ? strtotime($time['endTime']) + 86400 : time();
        
        $order = Order::order('create_time desc')
        ->where('create_time','between time',[$startTime,$endTime]);
        
        if($status != 'all'){
            $order->where('status',$status);
        }

        $result = $order->paginate(20);

        $customer_service = AdminUsers::column('id,account');
        for ($i=0; $i < count($result); $i++) { 
            $result[$i]['customer_service'] = $customer_service[$result[$i]['aid']];
        }

        $this->assign('time',$time);
		$this->assign('list',$result);
        return $this->fetch();
	}

	public function add(){
        if($this->request->isPost()){

            $file = $this->request->file("pic");
            $order_data = $this->request->post();

            //验证
            $validate = $this->orderValidate($order_data);
            if($validate['message'] != 'success'){
                $this->error($validate['message']);
            }

            //图片上传
            $pic = $this->orderPicUpload($file);
            $pic['message'] == 'success' ? $order_data['pic'] = $pic['data'] : $this->error($pic['message']);

            $order_data['aid'] = Session::get('aid');

            $rand = $order_data['aid'].substr(time(),7,3).mt_rand(1,10000000);
            $order_data['order_num'] = date('Ymd').substr($rand,1,8); 

            $this->order->save($order_data) ? $this->success('创建成功','admin/Order/index'):$this->error($this->order->getError());
        }
        else{
            return $this->fetch();
        }
    }

    public function edit(){
        if($this->request->isPost()){

            if(!$this->request->has('id')){
                $this->error('编辑失败');  
            }

            $file = $this->request->file("pic");
            $order_data = $this->request->post();

            //验证
            $validate = $this->orderValidate($order_data);
            if($validate['message'] != 'success'){
                $this->error($validate['message']);
            }

            //图片上传
            if(empty($file)){
                unset($order_data['pic']);
            }else{
                $pic = $this->orderPicUpload($file);
                $pic['message'] == 'success' ? $order_data['pic'] = $pic['data'] : $this->error($pic['message']);
            }
            $order_data['aid'] = Session::get('aid');
            $this->order->save($order_data,['id' => $order_data['id']])? $this->success('编辑成功'):$this->error($this->order->getError());
        }
        else{
            $id = $this->request->param('id');
            $id ? : $this->error('编辑失败');
            $result = $this->order->get($id);
            $this->assign('order',$result);
            return $this->fetch();
        }
    }

    /**
     * 订单删除
     * @return array
     */
    public function del(){
        if($this->request->isPost()) {
            $id = $this->request->post('id');
            if (!$this->request->has('id')) {
                $this->error('删除失败');
            }
            return Order::destroy(['id' => $id]) ? msgReturn(true,'success',null):msgReturn(false,$this->order->getError(),null);
        }
    }

    /**
     * 订单状态编辑
     * @return array
     */
    public function editStatus(){
        if($this->request->isPost()) {
            $data = [
                'id' => $this->request->post('id'),
                'status' => $this->request->post('status'),
            ];
            if (!$this->request->has('id')) {
                return msgReturn(false,'编辑失败',null);
            }
            return $this->order->save(['status' => $data['status']],['id' => $data['id']]) ? msgReturn(true,'编辑成功','success') : msgReturn(false,$this->order->getError(),null);
        }
    }

    /**
     * 客户姓名联想
     * [getCustomerName description]
     * @return [type] [description]
     */
    public function getCustomerName(){
        if($this->request->isGet()){
            $name = $this->request->get('name');
            $data = Order::all(function($query) use ($name){
                $query->where('user_contact','like',$name.'%')->field('user_contact')->distinct(true);
            });
            $data = collection($data)->toArray();
            return $data != null ? msgReturn(true,'success',$data) : msgReturn(false,'success',null);
        }
    }

    /**
     * [excel description]
     * @return [type] [description]
     */
    public function excel(){
        $time['startTime'] = $this->request->has('starttime') ? $this->request->param('starttime') : null;
        $time['endTime'] = $this->request->has('endtime') ? $this->request->param('endtime') : null;
        $status = $this->request->param('status');

        $status = ($status != null)||($status=='0') ? $status : 'all'; //防止状态0被过滤

        $result = $this->getOrderList($time,$status);

        $spreadsheet = new Spreadsheet();

        $picPath = ROOT_PATH . "public" . DS . "uploads". DS;
        $title = config('website.name').$time['startTime'].'-'.$time['endTime'];
        
        $spreadsheet->getActiveSheet()->setTitle($title);
        $spreadsheet->setActiveSheetIndex(0)
        ->setCellValue('A1', 'id')
        ->setCellValue('B1', '订单编号')
        ->setCellValue('C1', '产品名称')
        ->setCellValue('D1', '产品图片')
        ->setCellValue('E1', '客户名称')
        ->setCellValue('F1', '客户留言')
        ->setCellValue('G1', '订单备注')
        ->setCellValue('H1', '下单员')
        ->setCellValue('I1', '创建时间')
        ->setCellValue('J1', '订单状态')
        ->setCellValue('K1', '预算')
        ->setCellValue('L1', '定金');

        $num = count($result);
        for ($i=0; $i < $num; $i++) { 
            $index = $i+2;

            $spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(110);
            $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(15);

            $spreadsheet->getActiveSheet()->getRowDimension('1')->setRowHeight(15);
            $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(50);

            $spreadsheet->getActiveSheet()
            ->setCellValue('A'.$index, $result[$i]['id'])
            ->setCellValue('B'.$index, ' '.$result[$i]['order_num'])
            ->setCellValue('C'.$index, $result[$i]['jewel_name'])
            ->setCellValue('E'.$index, $result[$i]['user_contact'])
            ->setCellValue('F'.$index, $result[$i]['user_message'])
            ->setCellValue('G'.$index, $result[$i]['order_remark'])
            ->setCellValue('H'.$index, $result[$i]['customer_service'])
            ->setCellValue('I'.$index, $result[$i]['create_time'])
            ->setCellValue('J'.$index, $result[$i]['status'])
            ->setCellValue('K'.$index, $result[$i]['money'])
            ->setCellValue('L'.$index, $result[$i]['deposit']);

            $image = $picPath . $result[$i]['pic'];
            if(file_exists($image)){
                $drawing = new Drawing();
                $drawing->setName('产品图片');
                $drawing->setDescription('产品图片');
                $drawing->setPath($image);
                $drawing->setWidth(100);
                $drawing->setHeight(100);
                $drawing->setCoordinates('D'.$index);
                $drawing->setWorksheet($spreadsheet->getActiveSheet());    
            }else{
                $spreadsheet->getActiveSheet()->setCellValue('D'.$index, '图片不存在');
            }
            
        }

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$title.'.xls"');
        header('Cache-Control: max-age=0');

        $writer = IOFactory::createWriter($spreadsheet, 'Xls');
        $writer->save('php://output');
        exit;
    }

    /**
     * [getOrderList description]
     * @param  [type] $time   [description]
     * @param  [type] $status [description]
     * @return [type]         [description]
     */
    public function getOrderList($time,$status){
                
        $startTime = $time['startTime'] ? strtotime($time['startTime']) : 0;
        $endTime = $time['endTime'] ? strtotime($time['endTime']) + 86400 : time();

        $order = Order::order('create_time desc')
        ->where('create_time','between time',[$startTime,$endTime]);
        
        if($status != 'all'){
            $order->where('status',$status);
        }

        $result = $order->select();

        $order_type = config("website.order_type");
        $customer_service = AdminUsers::column('id,account');
        for ($i=0; $i < count($result); $i++) { 
            $result[$i]['customer_service'] = $customer_service[$result[$i]['aid']];
            $result[$i]['status'] = $order_type[$result[$i]['status']];
        }

        return $result;
    }

    /**
     * 订单验证函数
     * [orderValidate description]
     * @param  array  $order [description]
     * @return [type]        [description]
     */
    private function orderValidate($order = array()){
        $data = [
            'user_contact' => $order['user_contact'],
            'jewel_name' => $order['jewel_name'],
            'money' => $order['money'],
        ];

        $validate = Loader::validate('Order');

        $result = $validate->check($data) ? msgReturn(true,'success',null) : msgReturn(false,'error',$validate->getError());
        return $result;
    }

    /**
     * 图片上传
     * [orderPic description]
     * @param  [type] $file [description]
     * @return [type]       [description]
     */
    private function orderPicUpload($file){
        if (empty($file)) {
            return msgReturn(false,'请选择上传文件',null);
        }
        $info = $file->validate(['ext' => 'jpg,png,jpeg'])->move(ROOT_PATH . 'public' . DS . 'uploads'. DS );
        // if ($info) {
        //     $image = \think\Image::open($info->getSaveName());
        //     $image->thumb(500, 500)->save('thumb'.$info->getSaveName());
        // }
        $result = $info ? msgReturn(true,'success',$info->getSaveName()) : msgReturn(false,'error',null);
        return $result;
    }
}